import Card from '@/components/Card';
import Description, { GRID_CONF } from '@/components/Description';
import { lcControllerGetLastData, lcControllerGetLcRealTimeData } from '@/services/ess/deviceLc';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';
import { useModel } from '@@/exports';
import { Col, Row } from 'antd';
import type { DescriptionsItemType } from 'antd/es/descriptions';
import React, { useEffect, useRef, useState } from 'react';
import { useIntl } from 'umi';
import Chart from './RealtimeMonitorChart';

const RealtimeMonitor: React.FC = () => {
  let realtimeInterval = null as any;
  const intl = useIntl();
  const { initialState } = useModel('@@initialState');
  const [lcNodes, setLcNodes] = useState<API.LcNode[]>([]);
  const [isChildLC, setIsChildLC] = useState(false);
  const selectLCNodes = useRef<any>(null);
  const onLineOptions = useRef<any>(null);
  const workOptions = useRef<any>(null);
  const chargeOptions = useRef<any>(null);
  const [baseInfoColumns, setBaseInfoColumns] = useState<DescriptionsItemType[]>([
    {
      label: intl.formatMessage({ id: 'data.deviceFactory' }),
      key: 'producer',
      children: '',
    },
    {
      label: intl.formatMessage({ id: 'data.deviceModel' }),
      key: 'product',
      children: '',
    },
    {
      label: intl.formatMessage({ id: 'siteManage.deviceType' }),
      key: 'deviceType',
      children: '',
      span: 1,
    },
    {
      key: 'displayNone',
      label: '',
      children: '',
      hidden: true,
    },
  ]);
  const startInfoColumnsGLC: DescriptionsItemType[] = [
    {
      label: intl.formatMessage({ id: 'data.runningStatus' }),
      key: 'runState',
      children: '',
    },
    {
      label: intl.formatMessage({ id: 'data.gcbStatus' }),
      key: 'mainBreakerState',
      children: '',
    },
    {
      label: intl.formatMessage({ id: 'data.gcbFault' }),
      key: 'mainBreakerFault',
      children: '',
    },
    {
      label: intl.formatMessage({ id: 'systemManagement.neddTochange.subLCOnline' }),
      key: 'lcOnlineCount',
      children: '',
    },
    {
      label: intl.formatMessage({ id: 'systemManagement.neddTochange.subLCRunning' }),
      key: 'lcRunCount',
      children: '',
    },
    {
      label: intl.formatMessage({ id: 'systemManagement.neddTochange.subLCFault' }),
      key: 'lcFaultCount',
      children: '',
      span: 1,
    },
  ];
  const startInfoColumnsLC: DescriptionsItemType[] = [
    {
      label: intl.formatMessage({ id: 'data.onlineStatus' }),
      key: 'onlineState',
      children: '',
    },
    // {
    //   label: '目标功率值',
    //   key: 'aimPower',
    //   children: '',
    // },
    {
      label: intl.formatMessage({ id: 'data.runningStatus' }),
      key: 'lcRun',
      children: '',
    },
    {
      label: intl.formatMessage({ id: 'data.chargeDischargeStatus' }),
      key: 'bmsState',
      children: '',
    },
    {
      label: intl.formatMessage({ id: 'data.activePowerKw' }),
      key: 'activePower',
      children: '',
    },
    {
      label: intl.formatMessage({ id: 'data.reactivePowerKvar' }),
      key: 'reactivePower',
      children: '',
    },
    {
      label: intl.formatMessage({ id: 'data.maximumPower' }),
      key: 'ableMaxChgPower',
      children: '',
    },
    {
      label: intl.formatMessage({ id: 'data.maximumDischarge' }),
      key: 'ableMaxDchgPower',
      children: '',
    },
    {
      label: intl.formatMessage({ id: 'data.gcbStatus' }),
      key: 'mainBreakerState',
      children: '',
    },
    {
      label: intl.formatMessage({ id: 'data.gcbFault' }),
      key: 'mainBreakerFault',
      children: '',
    },
    {
      label: '子LC故障',
      key: 'powerMode',
      children: '',
      span: 1,
    },
  ];
  const [startInfoColumns, setStartInfoColumns] = useState(startInfoColumnsGLC);
  const [temperatureAndhumidityColumns, setTemperatureAndhumidityColumns] = useState<
    DescriptionsItemType[]
  >([
    {
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.deviceStatus' }),
      key: 'state',
      children: '',
    },
    {
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.onlineStatus' }),
      key: 'online',
      children: '',
    },
    {
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.onlineStatus' }),
      key: 'product',
      children: '',
    },
    {
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.ambientTemperature' }),
      key: 'temp',
      children: '',
    },
    {
      label: intl.formatMessage({ id: 'stationRealtimeMonitoring.ambientHumidity' }),
      key: 'humi',
      children: '',
      span: 1,
    },
  ]);
  const [strategyInfo, setStrategyInfo] = useState<DescriptionsItemType[]>([
    {
      label: intl.formatMessage({ id: 'data.powerMode' }),
      key: 'powerMode',
      children: '',
      span: 1,
    },
    // {
    //   label: '功率参数',
    //   key: 'powerTimeMsg',
    //   children: '',
    //   span: 1,
    // },
  ]);
  const getGLCInfo = () => {
    lcControllerGetLastData({ stationId: initialState?.stationId }).then((res) => {
      if (res.data) {
        let formatterData = JSON.parse(JSON.stringify(res.data)) || {};
        setBaseInfoColumns(
          baseInfoColumns.map((item) => {
            return {
              ...item,
              children: formatterData[item.key],
            };
          }),
        );
        setTemperatureAndhumidityColumns(
          temperatureAndhumidityColumns.map((item) => {
            return {
              ...item,
              children: formatterData.tempAndHumi ? formatterData.tempAndHumi[item.key] : '',
            };
          }),
        );
        setStartInfoColumns(
          startInfoColumnsGLC.map((item) => {
            return {
              ...item,
              children: formatterData[item.key],
            };
          }),
        );
        setLcNodes([res.data.root, ...res.data.nodes]);
      }
    });
  };
  const changeNode = (node) => {
    setIsChildLC(node.type === 'output');
    if (node.type === 'output') {
      selectLCNodes.current = node;
      lcControllerGetLcRealTimeData({ code: node.data.value.code }).then((res) => {
        if (res.data) {
          let FormatterData = JSON.parse(JSON.stringify(res.data)) || {};
          // 映射在线状态
          const onlineState = (onLineOptions?.current || []).find((item) => {
            return Number(item.value) === Number(FormatterData.onlineState);
          })?.label;
          FormatterData.onlineState = onlineState || '';
          // 映射工作状态
          const workState = (workOptions?.current || []).find((item) => {
            return Number(item.value) === Number(FormatterData.lcRun);
          });
          FormatterData.lcRun = workState?.label || '';
          const chargeState = (chargeOptions?.current || []).find((item) => {
            return Number(item.value) === Number(FormatterData.bmsState);
          });
          FormatterData.bmsState = chargeState?.label || '';
          setStartInfoColumns(
            startInfoColumnsLC.map((item) => {
              return {
                ...item,
                children: FormatterData[item.key],
              };
            }),
          );
          setStrategyInfo(
            strategyInfo.map((item) => {
              return {
                ...item,
                children: FormatterData[item.key],
              };
            }),
          );
        }
      });
    } else {
      getGLCInfo();
    }
  };
  const getDictOptions = () => {
    Promise.all([
      fetchDictInfo(DATABASE_TYPE_ENUM.ONLINE_STATUS),
      fetchDictInfo(DATABASE_TYPE_ENUM.WORK_STATUS),
      fetchDictInfo(DATABASE_TYPE_ENUM.CHARGE_STATUS),
    ]).then((res) => {
      onLineOptions.current = res[0];
      workOptions.current = res[1];
      chargeOptions.current = res[2];
    });
  };
  useEffect(() => {
    if (realtimeInterval) {
      clearInterval(realtimeInterval);
    }
    getDictOptions();
    realtimeInterval = setInterval(() => {
      if (selectLCNodes.current) {
        changeNode(selectLCNodes?.current);
      } else {
        getGLCInfo();
      }
    }, 60000);
    return () => {
      clearInterval(realtimeInterval);
    };
  }, []);
  return (
    <>
      <div>
        {lcNodes?.length > 0 && <Chart lcNodes={lcNodes} changeNode={changeNode} />}
        <Card
          title={intl.formatMessage({ id: 'systemManagement.neddTochange.basicData' })}
          className="global-secondary-card"
        >
          <Description items={baseInfoColumns} />
        </Card>
        <Card
          title={intl.formatMessage({ id: 'systemManagement.neddTochange.operationalInfo' })}
          className="global-secondary-card"
        >
          <Description items={startInfoColumns}></Description>
        </Card>
        {isChildLC ? (
          <Card
            title={intl.formatMessage({ id: 'menu.strategy' })}
            className="global-secondary-card"
          >
            <Row>
              <Col {...GRID_CONF}>
                <Description items={strategyInfo}></Description>
              </Col>
            </Row>
          </Card>
        ) : (
          <Card
            title={intl.formatMessage({ id: 'systemManagement.neddTochange.temperatureHumidity' })}
            className="global-secondary-card"
          >
            <Description items={temperatureAndhumidityColumns}></Description>
          </Card>
        )}
      </div>
    </>
  );
};

export default RealtimeMonitor;
